package q623_addOneRow;

import CommonClass.Common.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    /*
    给二叉树添加一行：
    只需要遍历到对应的行 然后将其加入到队列中 如果curDepth达到了 depth - 1 就结束层序遍历
    然后将队列中的节点依次出列 其对应的左右子树中间加一个节点即可
     */
    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        if (depth == 1) {
            TreeNode node = new TreeNode(val);
            node.left = root;
            return node;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int curDepth = 1;
        queue.offer(root);
        while (!queue.isEmpty()) {
            if (curDepth == depth - 1) break;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            curDepth++;
        }

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            TreeNode l = node.left;
            node.left = new TreeNode(val);
            node.left.left = l;

            TreeNode r = node.right;
            node.right = new TreeNode(val);
            node.right.right = r;
        }

        return root;
    }
}
